package com.heima.algorithm.dynamicprogramming;

import java.util.Arrays;

/**
 * 不同路径
 * @author 勾新杰
 * @version 1.0
 * @date 2024/11/6 12:15
 */
public class UniquePaths {

    /**
     * <h3>方法一：用二维数组进行动态规划</h3>
     * @param m 行数
     * @param n 列数
     * @return 路径总数
     */
    public static int uniquePaths1(int m, int n) {
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            dp[i][0] = 1;
        }
        for (int j = 0; j < n; j++) {
            dp[0][j] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        print(dp);
        return dp[m - 1][n - 1];
    }

    /**
     * <h3>方法二：将方法一的二维数组降维成一维数组进行优化</h3>
     * @param m 行数
     * @param n 列数
     * @return 路径总数
     */
    public static int uniquePaths2(int m, int n) {
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        for (int i = 0; i < m - 1; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] = dp[j - 1] + dp[j];
            }
        }
        System.out.println(Arrays.toString(dp));
        return dp[n - 1];
    }
    private static void print(int[][] dp){
        for (int[] ints : dp) {
            System.out.print("[ ");
            for (int anInt : ints) {
                System.out.printf("%03d ", anInt);
            }
            System.out.println("]");
        }
    }

    public static void main(String[] args) {
        int m = 7;
        int n = 7;
        int paths = uniquePaths2(m, n);
        System.out.println(paths);
    }
}
